/**
 * Global site variables and scripts
 */
var theme_url = "/public/themes/default/";

$(document).ready(function() { 
	/**
	 * Browser detection
	 */
	if ($.browser.webkit) { $('html').addClass('webkit'); }
	else if ($.browser.mozilla) { $('html').addClass('firefox'); }
	else if ($.browser.msie) { $('html').addClass('ie'); }
	else if ($.browser.opera) { $('html').addClass('opera'); }
	
	// Placeholder
	$.support.placeholder = 'placeholder' in document.createElement('input');
	if (!$.support.placeholder) {
		$('input[placeholder],textarea[placeholder]').each(function() {
			var input = $(this);
				input.before('<label class="placeholder">'+$(this).attr("placeholder")+'</label>');
			var label = $(this).siblings('label.placeholder');
			// On focus
			input.bind('focus', function() {
				label.hide();
			});
			label.bind('click', function() {
				label.hide();
				input.focus();
			});
			// On blur
			input.bind('blur', function() {
				if ($(this).val() == "") label.show();
			});
		});
	}
	
	/**
	 * Set up bookmark AJAX handler
	 */
	$("#crumbs-bookmark").ajaxForm({ 
		url: 'tasks/bookmark/add/ajax',
		dataType: 'json', 
    	beforeSubmit: function() {
			if ($(":input[name='bookmark_id']").val() != 0) {
				var ans = confirm(Lang.bookmarks_confirm_remove);
				if (!ans) {
					return false;
				}
			}
		},
		success: function(data) {
			if ($('#bookmarks-none').length) {
				$('#bookmarks-none').remove();
			}
			var b_input = $(":input[name='bookmark_id']").val();
			if (b_input == 0) {
				$("#bookmark-list").append(data.html);
				$(":input[name='bookmark_id']").val(data.id);
				$(":input[name='bookmark_img']").attr({src: data.img});
			} else {
				$("#bookmark-" + b_input).remove();
				if ($("#bookmark-list-" + b_input).length) $("#bookmark-list-" + b_input).remove();
				$(":input[name='bookmark_id']").val(0);
				$(":input[name='bookmark_img']").attr({src: data.img});
			}
		}
	}); 
	
	/**
	 * Bind events to drop downs
	 */
	$("#account-drop").bind("click", account_open);
	$(".account-dd").bind("mouseleave", account_timer);
	$(".account-dd").bind("mouseenter", account_canceltimer);
	
	$("#add-new-button").bind("click", addnew_open);
	$("#add-new-dd").bind("mouseleave", addnew_timer);
	
	$("#courses-button").bind("click", courses_open);
	$("#courses-dd").bind("mouseleave", courses_timer);
	
	/**
	 * Bind document click handler for color picker
	 */
	if ($("#color_picker").length) {
		$(document).bind('click', function(e) {
			var $clicked = $(e.target);
			if (!($clicked.is("#color_picker") || $clicked.is(".color-dropdown") 
					|| $clicked.is(".color-dropdown-course") || $clicked.parents().is("#color_picker"))) {
				$("#color_picker").hide();
			}
        });
	}
	
	/**
	 * Bind triggers to editor DOM elements
	 */
	objectsBind();
	editObjectsBind();
	
	/**
	 * Set up rounded corners on elements
	 * Autohide that which should be hidden
	 */
	if (! ($.browser.msie && parseFloat($.browser.version) <= 7)) {
		$("#nav li").corner("5px");
		//$("#right-classes li").corner("bevel 2px");
	}
	
	/**
	 * General on load events and binds
	 */
	if ($("#demo-signup").length) {
		$("#demo-signup").click(function() { 
			$('#modal-alert').modal(); 
			return false; 
		});
	}
	
	if ($("#invite-form").length) {		
		$('#invite-form').click( function() {	
			var school_invite = 0;
			if ($(this).attr('title') && $(this).attr('title').indexOf("school") != -1) {
				school_invite = 1;
			}
			var course_id = 0;
			if ($(this).attr('title') && $(this).attr('title').indexOf("course") != -1) {
				course_id = $(this).attr('title').replace("course", "");
			}
			$.ajax({
				url: "page/invites/getform/" + school_invite + "/" + course_id,
				type: "GET",
				dataType: "html",
				async: true,
				success: function(data){	
					$("#modal-window .title-header").html(Lang.invite_title);
					$("#modal-window .message").html(data);
					$("#modal-window #modal-window-action-button").hide();
					$("#modal-window .simplemodal-close").attr('value','Close');
					$("#modal-window .buttons").hide();
					$("#modal-window").modal({overlayClose:true});
					$("#modal-window").addClass("invite-contacts");
				},
				error: function(xhr, status, error){
					$('#ajax-error').html('<span>'+Lang.error_invite+'</span>').fadeIn();					
				}
			});	
			return false;
		});
	}
	
	$('.signup-modal-form').each( function() {
		var id = $(this).attr('id');
		var form = $(this);
		var skip = $('#skip-' + id);
		var loader = $('#' + id + '-loader');
		var href = $('#' + id + '-redirect');
		var error = $('#' + id + '-error');
		var skip_link = $('#' + id + '-cancel');
		
		$(this).ajaxForm({
			data: { ajax: 1 },
			type: 'post',
			dataType: 'json',
			beforeSubmit: function() {
				error.hide();
				loader.show();
			},
			success: function(data) {
				loader.hide();
				if (! data) {
					error.html(Lang.error_general);
					error.show();
					return false;
				} else if (data && data.status == "error") {
					error.html(URLDecode(data.message));
					error.show();
					return false;
				} else {
					location.href = href.attr('href');
				}
			}
		});
		
		skip_link.live('click', function(e) {
			skip.show();
			form.hide();
			e.preventDefault();
		});
	});
	
	$('.trial-type-button input').live('click', function() {
		$('.trial-type-button').removeClass('on');
		$(this).parent().addClass('on');
	});
	
	$('.skip-signup-modal-form').each( function() {
		var id = $(this).attr('id');
		var skip = $(this);
		var form_link = $('#' + id + '-cancel');
		var error = $(this).parent().find('.error');
		var loader = $('#' + id + '-loader');
		var href = $('#' + id + '-redirect');
		var form = $(this).prev();
		
		$(this).ajaxForm({
			data: { ajax: 1 },
			type: 'post',
			dataType: 'json',
			beforeSubmit: function() {
				error.hide();
				loader.show();
			},
			success: function(data) {
				loader.hide();
				if (! data) {
					error.html(Lang.error_general);
					error.show();
					return false;
				} else if (data && data.status == "error") {
					error.html(URLDecode(data.message));
					error.show();
					return false;
				} else {
					location.href = href.attr('href');
				}
			}
		});

		form_link.live('click', function(e) {
			skip.hide();
			form.show();
			e.preventDefault();
		});
	});
	
	/**
	 * Search modal
	 */
	
	$('.browse-courses-button').click( function(e) {
		$('#modal-window-courses-search-loader').hide();
		$("#modal-window-courses-search").modal({
			overlayClose: true, 
			focus: false,
			persist: true
		});
		e.preventDefault();
	});
	
	$('.search-result').live('click', function(e) {
		var resultcheck = $(this).find('.search-result-check'); 
		if (! $(e.target).is('input')){
			if (resultcheck.is(":checked")) {
				$(this).find('span').removeClass('checked');
				resultcheck.removeAttr('checked');
				$(this).removeClass('checked');
			} else {
				resultcheck.attr('checked','checked');
				$(this).addClass('checked');
				$(this).find('span').addClass('checked');
			}			
		} 
				
	});
	
	$('.search-result .checker').live('click', function () {
		if ($(this).find('span').hasClass('checked')) {			
			$(this).parents('.search-result').first().addClass('checked');
		} else {
			$(this).parents('.search-result').first().removeClass('checked');
		}	
	});
	
	$('.search-result-check').live('change', function() {
		if ($(this).is(":checked")) {
			$(this).parent().addClass('checked');
		} else {
			$(this).parent().removeClass('checked');
		}			
	});
	
	if ($('#unified-add').length > 0) {
		$('.course-select').change(function () {
			$('input.course-id').val($(this).val());
		});
		
		$('#assignment-course.course-select').change(function () {
			$('input.course-id').val($(this).val());
			$.ajax({
				url: "page/courses/gettypes/" + $(this).val(),
				type: "GET",
				dataType: "html",
				async: true,
				success: function(data){	
					$('#unified-more-type').html(data);
				},
				error: function(xhr, status, error){
					$('#ajax-error').html('<span>'+Lang.error_retrieve_assignment_types+'</span>').fadeIn();					
				}
			});
		});
	}
	
	if ($('#current-time').length) {
		cc_clock = $('#current-time');
		cc_split = cc_clock.html().split(':');
		cc_hours = parseInt(cc_split[0], 10);
		cc_minutes = parseInt(cc_split[1].substr(0, 2), 10);
		cc_timesuffix = cc_split[1].substr(2, 2);
		setTimeout("updateClock()", 60000);
		updateTopicNotify();
	}
		
	$(".css-hide").show();
});



/**
 * Global methods
 */
window.setTimeout(function() {
	$('.success').fadeOut(1000);
}, 30000);

/**
 * Account drop down menu
 */
var timeout    = 500;
var closetimer = 0;
var ddmenuitem = 0;

function account_open() {
	account_canceltimer();
	account_close();
	ddmenuitem = $("#account-dd").css("visibility", "visible");
}

function account_close() {
	if (ddmenuitem) {
		ddmenuitem.css("visibility", "hidden");
	}
}

function account_timer() {
	closetimer = window.setTimeout(account_close, timeout);
}

function account_canceltimer() {
	if (closetimer) {  
		window.clearTimeout(closetimer);
		closetimer = null;
	}
}

/**
 * Clock counter
 */
var cc_clock = null;
var cc_split = new Array();
var cc_hours = null;
var cc_minutes = null;
var cc_timesuffix = null;

function updateClock()
{
	cc_minutes = cc_minutes + 1;
	
	if (cc_minutes >= 60) {
		cc_hours = cc_hours + 1;
		cc_minutes = 0;
	}
	if (cc_hours > 11) {
		cc_timesuffix = (cc_timesuffix == "pm") ? "am" : "pm";
		cc_hours = cc_hours - 12;
	}
	if (cc_hours == 0) {
		cc_hours = 12;
	}
	if (cc_minutes < 10) {
		out_minutes = "0" + cc_minutes;
	} else {
		out_minutes = cc_minutes;
	}

	cc_clock.html(cc_hours + ":" + out_minutes + cc_timesuffix);
	setTimeout("updateClock()", 60000);
}

/**
 * Add new drop down menu (add-new)
 */
var an_timeout		= 500;
var an_closetimer 	= 0;
var an_ddmenuitem	= 0;

function addnew_open() {
	addnew_canceltimer();
	addnew_close();
	an_ddmenuitem = $("#add-new-dd").css("visibility", "visible");
}

function addnew_close() {
	if (an_ddmenuitem) {
		an_ddmenuitem.css("visibility", "hidden");
	}
}

function addnew_timer() {
	an_closetimer = window.setTimeout(addnew_close, timeout);
}

function addnew_canceltimer() {
	if (an_closetimer) {
		window.clearTimeout(an_closetimer);
		an_closetimer = null;
	}
}

/**
 * General use
 */
$(".add-submit .action-cancel").click(function() {
	var i = $(this).attr('rel');
	$('#'+i).hide();
	$(this).parent().parent().parent()[0].reset();
});

/**
 * Courses drop down menu
 */
var cd_timeout		= 500;
var cd_closetimer 	= 0;
var cd_ddmenuitem	= 0;

function courses_open() {
	courses_canceltimer();
	courses_close();
	cd_ddmenuitem = $("#courses-dd").css("visibility", "visible");
}

function courses_close() {
	if (cd_ddmenuitem) {
		cd_ddmenuitem.css("visibility", "hidden");
	}
}

function courses_timer() {
	cd_closetimer = window.setTimeout(courses_close, timeout);
}

function courses_canceltimer() {
	if (cd_closetimer) {
		window.clearTimeout(cd_closetimer);
		cd_closetimer = null;
	}
}


/**
 * Search results filtering
 */
function filterResults(keyword, selector) {
	$('.search-result').each(function () {
		if ($(this).find(selector).text().toLowerCase().indexOf(keyword) > -1) {
			$(this).show();
		} else {
			$(this).hide();
		}
	});
}

$('.filterbox').live('keyup', function () {
	var keyword = $(this).val().toLowerCase();
	var selector = $(this).attr('alt');
	filterResults(keyword, '.' + selector);
});

/**
 * Object edit and remove actions. Editing an object hides the passed in elt
 * and inserts the returned editor HTML code after it. Removing an object
 * prompts the user with the given message and then removes it from the page.
 * 
 * elt: object element to edit/remove
 * url: task url
 * par: parameters to be sent via POST
 * msg: alert prompt/message to display to user
 * ajx: whether the request is asynchronous or not
 */
function editObject(elt, url, par, msg) {
	elt.find(".icon").hide();
	elt.find(".loader").show();
	$.post(url, par,
  		function(data) {
			if (errorHandle(data)) return false;
			elt.hide();
			if (! $("#" + data.elt_id).length) elt.after(data.html);
			editObjectsBind();
			elt.find(".loader").hide();
			elt.find(".icon").show();
  		}, "json");
}

function removeObject(elt, url, par, msg, ajx) {
	var ans = confirm(msg);
	if (!ans) return false;
	elt.toggle();

	if (ajx) {
		$.post(url, par, function(data) {
			(errorHandle(data)) ? elt.toggle() : elt.remove();
		}, "json");
		return false;
	}
}

/**
 * Courses page
 */
$( function() {
	if ($("#new-item-date").length) $("#new-item-date").datepicker({ duration: '' });
}); 

$(".edit-item-date").each( function () {
	$(this).datepicker({ duration: '' });
});

$("#show-assignment-options").click(function() {
	$("#assignment-options").toggle();
});


/**
 * Notices
 */
$(".reminder-remove-a").click(function () {
	var ans = confirm(Lang.reminders_remove_prompt);
	if (!ans) return false;
	var url = $(this).attr("href") + "/ajax";
	$.post(url, '', errorHandle, "json");
	$(this).parent().remove();
	return false;
});

/**
 * Reminders page
 */
function objectsBind(){
	$(".reminder-object").each(function(){
		var elt = $(this);
		var id = getObjectID($(this).attr("id"));
		var params = "id=" + id + "&ajax=1";
		
		$(this).find(".reminder-edit").click(function(){
			editObject(elt, "tasks/reminder/editor", params, "");
			return false;
		});
		
		$(this).find(".reminder-remove").click(function(){
			removeObject(elt, "tasks/reminder/remove/" + id + "/ajax", "", Lang.reminders_remove_prompt, true);
			return false;
		});
		
		$(this).find(".announcement-remove").click(function(){
			removeObject(elt, "tasks/reminder/removeannouncement/" + id + "/ajax", "", Lang.announcements_remove_prompt, true);
			return false;
		});
	}); // Reminder object
	
	$(".remove-file-manager").click(function () {
		var $id = getObjectID($(this).attr("id"));
		removeObject($("#file-" + $id), $(this).attr("href") + "/ajax", "", Lang.files_remove_prompt, true)
		return false;
	}); // Remove file
}

/**
 * Bookmarks
 */
$('.bookmark-edit').live('click', function(e){
	var id = getObjectID($(this).attr('id'));
	$('#bookmark-edit-form-' + id).toggleClass('hide');
	$('#bookmark-url-' + id).toggleClass('hide');
	e.preventDefault();
});

function editObjectsBind() {
	$(".edit-reminder").each(function () {
		var elt = $(this);
		var id = getObjectID($(this).attr("id"));

		$(this).ajaxForm({
			url: 'tasks/reminder/edit/ajax',
			dataType: 'json', 
			beforeSubmit: function() {
				elt.find(".icon").hide();
				elt.find(".loader").show();
			},
			success: function(data) {
				elt.find(".loader").hide();
				elt.find(".icon").show();
				elt.prev().remove();
				elt.hide();
				elt.after(data.html);
				elt.remove();
				objectsBind();
			}
		});
	}); // Edit Reminder
	
	$(".edit-item-date").each( function () {
		$(this).datepicker({ duration: '' });
	});
}

$('form.edit-reminder .action-cancel').live('click', function() {
	var elt = $(this).parent().parent();
	elt.hide();
	elt.prev().show();
	elt.remove();
});

$("form.edit-reminder select[name='location']").live('change', function () {
	if ($(this).val() == 3) {
		$(this).next().attr("disabled", "");
	} else {
		$(this).next().attr("disabled", "disabled");
		$(this).next().val("");
	}
}); // we may not need this after the edit to the function below

$("#nr_location").live('change', function () {
	if ($(this).val() == 3) {
		$(this).next().attr("disabled", "");
	} else {
		$(this).next().attr("disabled", "disabled");
		$(this).next().val("");
	}
});

$("#nr_name").focus(function () { 
	$("#reminder-additional").show();
});

$("#nr-cancel").click(function() {
	$("#reminder-additional").hide();
});

/**
 * Announcements
 */
$("#show-add-announcement-form").click(function() {
	$("#add-announcement").show();
});

$(".show-reply-announcement-form").click(function() {
	$("#message-reply").show();
	$("#bottom-reply-button").parent().parent().parent().hide();
});

/**
 * Files page
 */
$(".course_name a").click(function () {
	$(this).parent().parent().next().toggle();
	$(this).toggleClass("closed");
	$(this).parent().parent().toggleClass("course-closed");
});

$(".add-file a").click(function () {
	$(this).toggle();
	$(this).parent().next().toggle();
});

$(".add-file-form a").click(function() {
	$(this).closest("div").toggle();
	$(this).closest("div").prev().children("a").toggle();
});

$(".file-upload-form").each(function() {
	var $me = $(this);
	var id = getObjectID($me.attr("id"));
	var $container = $("#coursefiles-" + id);
	
	$(this).ajaxForm({
		url: $(this).attr('action'),
		dataType: 'json',
		iframe: true,
		beforeSubmit: function() {
			$me.find(".progress").toggle();
		},
		success: function(data) {
			var $html = URLDecode(data.html);
			$me.find(".progress").toggle();
			$container.find(".no-files-note").hide();
			if (errorHandle(data)) return false;
			$container.find(".course-table:first tr:last").after($html);
			objectsBind();
		}
	})
	
	/**
	 * Disable all buttons
	 */
	$('.button.disabled').unbind('click');
});

/**
 * Calendar functions
 */
function loadMonth(date, msg) {
	$("#calendar-loader").show();
	var params = "date=" + date + "&ajax=1";
	
	$.post("tasks/calendar/load", params, function(data){
		$("#calendar-loader").hide();
		$("#c").html(data.html);
	}, "json");
}

$('.show-more-events').click(function(e) {
	$(this).parent().find('.event').css('display', 'block');
	$(this).hide();
	e.preventDefault();
});

/**
 * Discussions functions
 */

$('.new-message').click(function (e) {
	$("#modal-window-discussion-new").modal({
		overlayClose: true, 
		focus: false,
		persist: true
	});
});

$(".add-topic").click(function () {
	$("#add-topic").toggle();
});

$("#topic-audience").change(function () {
	updateTopicNotify();
});

function updateTopicNotify() {
	if (! $("#topic-audience").length) {
		return false;
	}
	
	var id = $("#topic-audience").val();
	var support_course_id = $("#support-course-id").val();
	
	if (isNumeric(id) && id > 0 && id != support_course_id) {
		$("#notify-class-checkbox").removeAttr('disabled');
		$("#notify-class-span").removeClass('disabled');
		$("#sticky-class-checkbox").removeAttr('disabled');
		$("#sticky-class-span").removeClass('disabled');
	}
	else {
		$("#notify-class-checkbox").attr('disabled', true);
		$("#notify-class-span").addClass('disabled');
		$("#sticky-class-checkbox").attr('disabled', true);
		$("#sticky-class-span").addClass('disabled');
	}
}

$(".cancel-add-topic").click(function () {
	$("#new-item-form").clearForm();
	$("#topic-audience").val("-1");
	//$("#new-item-date").val($("#new-item-date")[0].defaultValue);
	$("#new-item-hour").val("0");
	$("#new-item-minute").val("0");
	$("#new-item-ampm").val("am");
	$("#add-topic-link").blur();
	$("#new-item-description").hide();
	$("#lock-date-el").hide();
});

$("#add-topic-title").focus(function () {
	$("#new-item-description").show();
});

$(".topic-details-more").click(function () {
	$("#message" + $(this).attr("rel")).toggle();
});

$(".delete-topic-a").click(function () {
	var ans = confirm(Lang.discussions_remove_topic);
	if (!ans) return false;
});

function flagMessage() {
	var ans = confirm(Lang.discussions_flag_topic);
	if (!ans) return false;
}

$(".wysiwyg").each(function() {
	if (typeof($(this).contentEditable) != null && $("html").hasClass("no-touch")) {
		/*$(this).uEditor({
			insertParagraphs : false,
			stylesheet : '/public/themes/default/stylesheets/uEditor.css',
			toolbarItems : ['bold','italic','link','image','orderedlist','unorderedlist','htmlsource','formatblock'],
			containerClass : 'uEditor'
		});*/
		$(this).wysiwyg();
	}
});

$('#toggle-advanced').click(function () {
	$(".advanced-option").toggle();
});

$('#set-lock').attr('checked', false);
$('#set-lock').click(function () {
	$('#lock-date-el').toggle();	
	
});

$('.reply-to-message').click(function () {
	var id = $(this).attr('id').replace('reply-to-message-', '');
	$('#reply-to-message-form-' + id).toggle();	
});

$('.reply-to-message-cancel').click(function () {
	$('#reply-to-message-form-' + $(this).attr('id').replace('reply-to-message-cancel-', '')).toggle();	
});

$("#add-topic-link").blur(function () {
	$('#add-topic-link-loader').show();
	var q = $('#add-topic-link').val();
	if (q == '') {
		$('#add-media-preview').html('');
		$('#media-preview-row').hide();
		$('#add-topic-link-loader').hide();
		return false;
	} else {
		$('#media-preview-row').show();
	}		
	
	var regexp = /(http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?/
		
	if (! regexp.test(q)) {
		$('#add-link-error').show();
		$('#add-link-error').html(Lang.error_invalid_link);
		$('#add-topic-link-loader').hide();
		return false;
	}			
	
	$.embedly(q, { maxWidth: 150, wrapElement: 'div' }, function(oembed){
		$('#add-topic-link-loader').hide();
		if (oembed == null) {
			$('#add-media-preview').html('');
			$("#add-link-error").html(Lang.discussions_no_preview);
			$('#add-link-error').show();
		} else {
			$('#add-link-error').hide();
			$("#add-media-preview").html(oembed.code);
			$("#media-embed-code").val(oembed.code);
			$("#media-embed-thumbnail").val(oembed.thumbnail_url);
		}
	});

});

if ($('#add-topic-link').length && $('#add-topic-link').val() != '') {
	$('#media-preview-row').show();
	$.embedly($('#add-topic-link').val(), {maxWidth: 150, wrapElement: 'div' }, function(oembed){
		if (oembed == null) {
			$('#add-media-preview').html('');
			$("#add-link-error").html(Lang.discussions_no_preview);
			$('#add-link-error').show();
		} else {
			$('#add-link-error').hide();
			$("#add-media-preview").html(oembed.code);
			$("#media-embed-code").val(oembed.code);
		}
	});
}

$('.media-modal').each(function () {
	var $msg = $(this);
	var url = $(this).attr('href');
	$.embedly(url, {maxWidth: 200, wrapElement: 'div' }, function(oembed){
		if (oembed == null) {
			$("#modal-window-media .message").html(Lang.problem_loading_media_1 + url + Lang.problem_loading_media_2);
			$("#modal-window-media").modal({overlayClose:true});
		} else {
			var $preview = $msg.parents('.topic-info').find('.media-preview'); 
			$preview.html(oembed.code + '<div style="display:block;margin:5px 0 10px;"><a target="_blank" href="' + url + '">' + Lang.discussions_view_original + '</a></div>');
			$preview.show();
		}
	});
});

$('.media-modal').click(function (e) {
	var url = $(this).attr('href');
	var title = $(this).attr('title');
	
	$.embedly(url, {maxWidth: 400, wrapElement: 'div' }, function(oembed){
		if (oembed == null) {
			$("#modal-window-media .message").html(Lang.problem_loading_media_1 + url + Lang.problem_loading_media_2);
			$("#modal-window-media").modal({overlayClose:true});
		} else {
			$("#modal-window-media .title-header").html(title);
			$("#modal-window-media .message").html(oembed.code + '<div style="display:block;margin:5px 0 10px;"><a target="_blank" href="' + oembed.url + '">' + Lang.discussions_view_original + '</a></div>');
			$("#modal-window-media").modal({overlayClose:true});
			return false;
		}
	});
	e.preventDefault();
	return false;
});

var request_pending = false;

function place_vote(voteReceived, message_id, remove) {	
	if (! request_pending) {
		request_pending = true;
		$.post("tasks/discussion/set_post_vote", 
			{ vote: voteReceived,
		 	  message_id: message_id,
		 	  remove: remove,
			  ajax: 1 },
  			function(data) {
				
				request_pending = false;
				if (data == "")
					alert(lang.error_save_vote);
				else
					$("#message-score" + message_id).html(data);
		    }
  		, "html");
  	}
  	return false;
}

$('.vote.up').click(function () {
	var id = $(this).attr('id').replace('vote-up', '');

	var remove = $(this).hasClass('on');
		
	if (remove) {
		$(this).removeClass('on');
		$(this).addClass('off');
		$('#vote-down' + id).removeClass('on');
		$('#vote-down' + id).addClass('off');
	} else {
		$(this).removeClass('off');
		$(this).addClass('on');
		$('#vote-down' + id).removeClass('on');
		$('#vote-down' + id).addClass('off');
	}
	
	place_vote(1, id, remove);
		
});

$('.vote.down').click(function () {
	var id = $(this).attr('id').replace('vote-down', '');

	var remove = $(this).hasClass('on');
	
	if (remove) {
		$(this).removeClass('on');
		$(this).addClass('off');
		$('#vote-up' + id).removeClass('on');
		$('#vote-up' + id).addClass('off');
	} else {
		$(this).removeClass('off');
		$(this).addClass('on');	
		$('#vote-up' + id).removeClass('on');
		$('#vote-up' + id).addClass('off');
	}
	
	place_vote(-1, id, remove);
		
});

$('.flag').click(function () {
	var id = $(this).attr('id').replace('flag', '');

	var remove = $(this).hasClass('on');
		
	if (remove) {
		$(this).removeClass('on');
		$(this).addClass('off');		
	} else {
		$(this).removeClass('off');
		$(this).addClass('on');
		
	}
	
	$.post("tasks/discussion/flag/" + id, 
		{ ajax: 1 },
		function(data) {
			
			request_pending = false;
			if (data != "")
				alert(lang.error_save_vote);			
	    }
	, "html");
		
});

$('.unflag').click(function () {
	var id = $(this).attr('id').replace('unflag', '');
	
	$.post("tasks/discussion/unflag/" + id, 
		{ ajax: 1 },
		function(data) {
			
			if (data == "")
				alert(lang.error_unflagged_msg);
			else
				$('#topic-' + id).remove();
	    }
	, "html");
		
});

$('.delete-msg').click(function () {
	var id = $(this).attr('id').replace('delete-msg-', '');
	
	$.post("tasks/discussion/delete/" + id, 
		{ ajax: 1 },
		function(data) {
			if (data == "")
				alert(lang.error_delete_msg);
			else
				$('#topic-' + id).remove();
	    }
	, "html");
		
});

$('.show-discussion-reply').click(function() {
	$('#add-reply').show();
	$('html, body').animate({scrollTop: $("#add-reply").offset().top},500);
	$('#discussion-reply-bottom').hide();
});

$('.cancel-discussion-reply').click(function() {
	$(this).parent().parent()[0].reset();
	$('#add-reply').hide();
	$('#discussion-reply-bottom').show();
});


/**
 * Settings functions
 */
function saveCalendarColor(color_id, color, ajax) {
	ajax = ajax || false;
	var id = "#" + $("#cid").val();
	var cid = $("#ccid").val();
	$(id).val(color_id);
	$(id + "_selection").css("background-color", color);
	$("#course_li_" + cid).css("background-color", color);
	$(id + "_name").css("color", color);
	$("#color_picker").toggle();
	if (ajax) {
		$.post("tasks/settings/calendar/ajax", { course_id: cid, color_id: color_id } );
	}
}

$(".color-dropdown").click(function (e) {
	var position = $(this).position();
	$("#color_picker").css({ 'top': position.top + 15, 'left': position.left + 3 });
	$("#cid").val("course" + getObjectID($(this).attr("id")));
	$("#ccid").val(getObjectID($(this).attr("id")));
	$("#color_picker").toggle();
});

/**
 * Settings: Rubrics
 */
$("#rubric-add-row").click(function (e) {
    var n = $('.rubric-line').length; // get the number of inputs (8/28/11, this was changed to removed the length - 1; b/c of markup changes)
    var o = n + 1;
    var $last = $('.rubric-line').last();
    var $x = $last.clone();
    
    $x.attr('id', 'rubric-line-' + o);
    $x.find('input.range-letter').attr({ value: '', name: 'rl_' + o});
    $x.find('input.range-start').attr({ value: '', name: 'rt_' + o});
    //$x.children('input[name*=rl]').attr('value','').attr('name', 'rl_' + o);
    //$x.children('input[name*=rt]').attr('value','').attr('name', 'rt_' + o);
    
    $last.after($x);
});
/*
$("#rubric-add-row").click(function (e) {
	var $n = $('.rubric-line').length; // get the number of inputs (8/28/11, this was changed to removed the length - 1; b/c of markup changes)
	var $o = $n + 1;
	var $x = $('#rubric-line-' + $n).clone().attr('id', 'rubric-line-' + $o);
		$x.children('input[name*=rl]').attr('value','').attr('name', 'rl_' + $o);
		$x.children('input[name*=rt]').attr('value','').attr('name', 'rt_' + $o);
	$('#rubric-line-' + $n).after($x);
});
*/
$('#rubric-form').submit(function() {
	var f = $(':input[title=rubric]').serializeArray();
	var j = $.JSON.encode(f);
	$('#rubric-add-vars').empty();
	$('#rubric-add-vars').attr('value', j);
});

$('.rubric-delete').click(function (e) {
	var id = $(this).attr('id');
	var ans = confirm(Lang.rubric_delete_confirm);
	if (!ans) return false;
});

$('.rubric-details').click(function () {
	var d = '';
	var i = $(this).attr('id').substr(7);
	var t = $(this).attr('title');
	var p = "rubric_id=" + i + "&ajax=1";
	
	var loader = $(this).next();
	loader.css('visibility', 'visible');

	$.ajax({
		url: "tasks/settings/rubricdetails",
		type: "POST",
		data: ({rubric_id: i, ajax: 1}),
		dataType: "json",
		async: true,
		success: function(data){	
			$.each(data, function(i, item) {
				d = d + '<tr><td class="left">'+item.letter+'</td><td>'+item.threshold+'</td></tr>';
			});
			$("#modal-window .title-header").html(t);
			$("#modal-window .message").html('<p>'+Lang.rubric_modal+'</p><table class="rubric-modal-line">'+d+'</table>');
			$("#modal-window #modal-window-action-button").hide();
			$("#modal-window .simplemodal-close").attr('value','Close');
			$("#modal-window .buttons").show();
			$("#modal-window").modal({overlayClose:true});
			loader.css('visibility', 'hidden');
		},
		error: function(xhr, status, error){
			$('#ajax-error').html('<span>'+Lang.rubric_baddetails+'</span>').fadeIn();
			loader.css('visibility', 'hidden');
		}
	});
	
	return false;
});

/**
 * Settings: Terms
 */
$("#term-add-row").click(function (e) {
	var $n = $('.term-line').length; // get the number of inputs (8/28/11, this was changed to removed the length - 1; b/c of markup changes)
	var $o = $n + 1;
	var $x = $('#term-line-' + $n).clone().attr('id', 'term-line-' + $o);
		$x.children('input[name*=tn]').attr('value','').attr('name', 'tn_' + $o);
		$x.children('input[name*=ts]').attr('value','').attr('name', 'ts_' + $o);
		$x.children('input[name*=te]').attr('value','').attr('name', 'te_' + $o);
	$('#term-line-' + $n).after($x);
	$('#term-line-' + $o).children('.range-start').datepicker({ duration: '' });
});

$('#term-form').submit(function() {
	var f = $(':input[title=term]').serializeArray();
	var j = $.JSON.encode(f);
	$('#term-add-vars').empty();
	$('#term-add-vars').attr('value', j);
});

$('.term-delete').click(function (e) {
	var id = $(this).attr('id');
	var ans = confirm(Lang.term_delete_confirm);
	if (!ans) return false;
});

$('.term-details').click(function () {
	var d = '';
	var i = $(this).attr('id').substr(5);
	var t = $(this).attr('title');
	var p = "term_id=" + i + "&ajax=1";
	
	var loader = $(this).next();
		loader.css('visibility', 'visible');
	
	$.ajax({
		url: "tasks/settings/termdetails",
		type: "POST",
		data: ({term_id: i, ajax: 1}),
		dataType: "json",
		async: true,
		success: function(data){
			$.each(data, function(j, item) {
				d = d + '<tr><td class="left">'+item.name+'</td><td class="date">'+item.start.substr(5,2)+'/'+item.start.substr(8,2)+'/'+item.start.substr(0,4)+'</td><td class="date">'+item.end.substr(5,2)+'/'+item.end.substr(8,2)+'/'+item.end.substr(0,4)+'</td></tr>';
			});
			$("#modal-window .title-header").html(t);
			$("#modal-window .message").html('<p>'+Lang.term_modal+'</p><table class="term-modal-line">'+d+'</table>');
			$("#modal-window #modal-window-action-button").hide();
			$("#modal-window .simplemodal-close").attr('value','Close');
			$("#modal-window .buttons").show();
			$("#modal-window").modal({overlayClose:true});
			loader.css('visibility', 'hidden');
		},
		error: function(xhr, status, error){
			$('#ajax-error').html('<span>'+Lang.term_baddetails+'</span>').fadeIn();
			loader.css('visibility', 'hidden');
		}
	});
	
	return false;
});

/**
 * Settings: Account
 */
$( function() {
	if ($("#downgrade-confirm").length) {
		$("#downgrade-confirm").click(function(){
			($(this).attr("checked")) ? $("#downgrade-button").removeAttr('disabled') : $("#downgrade-button").attr("disabled", "disabled"); 
		});
	}
}); 

/**
 * School pages
 */
$( function() {
	if ($("#invite-users").length) {
		$("#invite-users").click(function(e){
			alertMessage($('#invite-users-title').html(), $('#invite-users-message').html());
			e.preventDefault();
		});
	}
});

/**
 * General page elements
 */
$('button.cb, button.button').live('click', function() {
	var a = $(this).find('a');
	if (a && a.attr('href')) {
		location.href = a.attr('href');
		return false;
	}
});

/**
 * Utility functions
 */
$(".date-picker").each(function() {
	if ($(this).hasClass('no-future')) {
		$(this).datepicker({ duration: '', maxDate: '+0d' });
	}
	else if ($(this).hasClass('no-past')) {
		$(this).datepicker({ duration: '', minDate: '+0d' });
	}
	else {
		$(this).datepicker({ duration: '' });
	}
});

function getObjectID(elt_id) {
	return elt_id.substring(elt_id.lastIndexOf("-") + 1);
}

function getFileName(path) {
	return path.substring(path.lastIndexOf("/") + 1);
}

function isNumeric(input)
{
   return (input - 0) == input && input.length > 0;
}

if (!Array.prototype.indexOf)
{
	Array.prototype.indexOf = function(elt /*, from*/)
	{
		var len = this.length;

		var from = Number(arguments[1]) || 0;
		from = (from < 0)
         	? Math.ceil(from)
         	: Math.floor(from);
        if (from < 0)
        	from += len;

        for (; from < len; from++)
        {
        	if (from in this && this[from] === elt)
        		return from;
        }
        return -1;
	};
}

function removeArrayValue(array, value)
{
	var idx = array.indexOf(value);
	if(idx != -1) {
		array.splice(idx, 1);
	}
	return array;
}

function errorHandle(data) {
	if (data && data.status == "error") {
		$("#modal-message .title h3").html(Lang.error_problem);
		$("#modal-message .message").html(URLDecode(data.message));
		$("#modal-message").modal({overlayClose:true});
		return true;
	}
	return false;
}

function errorHandleModal(data) {
	if (data.status == "error") {
		$('#modal-error').html(URLDecode(data.message));
		$('#modal-error').show();
		return true;
	}
	return false;
}

function errorMessage() {
	$("#modal-message .title h3").html(Lang.error_problem);
	$("#modal-message .message").html(Lang.error_general);
	$("#modal-message").modal({overlayClose:true});
	return true;
}

function URLDecode(url) {
	var o = url;
	var binVal, t, b;
	var r = /(%[^%]{2}|\+)/;
	while ((m = r.exec(o)) != null && m.length > 1 && m[1] != '') {
		if (m[1] == '+') {
			t = ' ';
		} else {
			b = parseInt(m[1].substr(1), 16);
			t = String.fromCharCode(b);
		}
		o = o.replace(m[1], t);
	}
	return o;
}

function alertMessage(title, message) {
	title = title || Lang.error_problem;
	message = message || Lang.error_general;
	$("#modal-message .title h3").html(title);
	$("#modal-message .message").html(message);
	$("#modal-message").modal({overlayClose:true});
}

/**
 * Links with class "new-window" open in a new window
 */
$('.new-window').click(function(e) {
	window.open(this.href, '_blank');
	e.preventDefault();
	return false;
});

/**
 * Validation rule
 */
$("#signupForm").validate({
    rules: {
        fname: "required",
        lname: "required",
        username: {
            required: true, 
            minlength: 4
        },
        password: {
            required: true,
            minlength: 6
        },
        email: {
            required: true,
            email: true
        },
        agree: "required"
    },
    errorPlacement: function(error, element) { 
        if ( element.is(":radio") ) 
            error.appendTo( element.parent().next().next() ); 
        else if ( element.is(":checkbox") ) 
            error.appendTo ( element.parent() ); 
        else 
            error.appendTo (element.parent());
    },
    messages: {
        firstname: Lang.error_firstname,
        lastname: Lang.error_firstname,
        username: {
            required: Lang.error_username_req,
            //remote: Lang.error_username_taken,
            minlength: Lang.error_username_length
        },
        password: {
            required: Lang.error_password_req,
            minlength: Lang.error_password_length
        },
        email: Lang.error_email,
        agree: Lang.error_terms
    },
    success: function(label) { 
        // set as text for IE 
        label.html(" ").addClass("valid"); 
    }
});

/**
 * Disable all buttons
 */
$('.button.disabled').unbind('click');
